package com.lw.leetcode.linked;

/**
 * 234. 回文链表
 * 面试题 02.06. 回文链表
 *
 * @Author liw
 * @Date 2021/5/14 9:09
 * @Version 1.0
 */
public class IsPalindrome {

    public static void main(String[] args) {
        IsPalindrome test = new IsPalindrome();
        boolean palindrome = test.isPalindrome(ListNode.getInstance());
        System.out.println(palindrome);
    }

    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode mid = getMid(head);
        ListNode end = reversal(mid);
        return compare(head, end);
    }

    /**
     * 头尾比较
     *
     * @param a 头
     * @param b 尾
     * @return 是否回文
     */
    private boolean compare(ListNode a, ListNode b) {
        while (a != null && b != null) {
            if (a.val != b.val) {
                return false;
            }
            a = a.next;
            b = b.next;
        }
        return true;
    }

    /**
     * 反转链表
     *
     * @param node 头
     * @return 反转后的头
     */
    private ListNode reversal(ListNode node) {
        if (node == null || node.next == null) {
            return node;
        }
        ListNode a = node;
        ListNode b = node.next;
        a.next = null;
        while (b != null) {
            ListNode c = b.next;
            b.next = a;
            a = b;
            b = c;
        }
        return a;
    }

    /**
     * 获取链表中点
     *
     * @param node 头
     * @return 中点
     */
    private ListNode getMid(ListNode node) {
        ListNode a = node;
        ListNode b = node;
        while (b != null && b.next != null) {
            a = a.next;
            b = b.next.next;
        }
        return a;
    }

}
